package com.lab.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lab.common.constant.ProductConstant;
import com.lab.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.lab.gulimall.product.dao.AttrGroupDao;
import com.lab.gulimall.product.dao.CategoryDao;
import com.lab.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.lab.gulimall.product.entity.AttrGroupEntity;
import com.lab.gulimall.product.entity.CategoryEntity;
import com.lab.gulimall.product.service.CategoryService;
import com.lab.gulimall.product.vo.AttrGroupRelationVo;
import com.lab.gulimall.product.vo.AttrResoVo;
import com.lab.gulimall.product.vo.AttrVo;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lab.common.utils.PageUtils;
import com.lab.common.utils.Query;

import com.lab.gulimall.product.dao.AttrDao;
import com.lab.gulimall.product.entity.AttrEntity;
import com.lab.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResoVo> ResoVos = records.stream().map((attrEntity) -> {

            AttrResoVo attrResoVo = new AttrResoVo();
            BeanUtils.copyProperties(attrEntity, attrResoVo);
            if ("base".equalsIgnoreCase(type)) {
                //1、设置分类和分组的名字
                AttrAttrgroupRelationEntity attr_id = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().
                        eq("attr_id", attrEntity.getAttrId()));
                if (attr_id != null && attr_id.getAttrGroupId()!=null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attr_id.getAttrGroupId());
                    attrResoVo.setGroupName(attrGroupEntity.getAttrGroupName());

                }
            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResoVo.setCatelogName(categoryEntity.getName());
            }
            return attrResoVo;
        }).collect(Collectors.toList());
        pageUtils.setList(ResoVos);
        return pageUtils;
    }

    @Autowired
    private AttrAttrgroupRelationDao relationDao;
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        //1.保存基本的数据,保存后他的主键ID会返回到原有的对象attrEntity
        this.save(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() &&
                attr.getAttrGroupId() != null) {

            //2。保存关联关系
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            System.out.println(attrEntity.getAttrId());
            relationDao.insert(attrAttrgroupRelationEntity);
        }

    }

    @Autowired
    CategoryService categoryService;
    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrResoVo getAttrInfo(Long attrId) {
        AttrResoVo attrResoVo = new AttrResoVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrResoVo);
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao.selectOne(new
                    QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",
                    attrEntity.getAttrId()));
            //1.设置分组信息设置
            if (attrAttrgroupRelationEntity != null) {
                attrResoVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity =
                        attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrResoVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    System.out.println(attrGroupEntity.getAttrGroupName());
                }
            }
        }



        //2.设置分类信息
        Long catelogId = attrResoVo.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogIds(catelogId);
        System.out.println(catelogPath.length);
        attrResoVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrResoVo.setCatelogName(categoryEntity.getName());
        }
        System.out.println(attrResoVo.toString());
        return attrResoVo;

    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //1.修改关联分组
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            //2.
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                relationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().
                                eq("attr_id", attr.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }
        }

    }
    /*
    * 根据分组id查找所有关联的基本属性
    *
    * */
    @Override
    public List<AttrEntity> getRelationArr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq(
                "attr_group_id", attrgroupId)
        );
        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
//        relationDao.delete(new QueryWrapper<>().eq("attr__id", 1L)
//                .eq("attr_group_id", 1));
        //批量删除
        List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(entities);
        System.out.println("I am Ok");
    }
    /*
    * 获取当前分组没有关联到的所有属性
    * */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        //1/当前分组只能关联自己所属分类的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2 .当前分组只能关联别的分组没有引用的属性
            //2.1当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId).ne("attr_group_id", attrgroupId));
        List<Long> collect = group.stream().map((item) -> {
            System.out.println("item:" + item);
            return item.getAttrGroupId();

        }).collect(Collectors.toList());
        System.out.println("--------------------------------------------------------------");
        //2.2和属性分组关联的所有属性，假设闯进来的是4组：外壳
        List<AttrAttrgroupRelationEntity> groudId = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrgroupId));
        List<Long> attrIds = groudId.stream().map((item) -> {
            System.out.println("getAttrId:" + item.getAttrId());
            return item.getAttrId();
        }).collect(Collectors.toList());
        System.out.println("--------------------------------------------------------------");
        //找到的是外壳4下面的所有属性7
        //2.3从当前分类中所有属性中移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().
                eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds != null & attrIds.size() > 0) {
            queryWrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isNullOrEmpty(key)) {
            queryWrapper.and((w)->{
                w.eq("attr_id", key).or().like("attr_name", key);

            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        /*
        * Select attr_i from pms_attr where attr_i in(?) and search_type = 1
        *
        * */
        return  baseMapper.selectSearchAttrs(attrIds);
    }

}